from django.db import models
from django.contrib.auth.models import User

class Family(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField(blank=True)
    invite_code = models.CharField(max_length=10, unique=True)
    avatar_url = models.URLField(blank=True)
    max_members = models.IntegerField(default=10)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    STATUS_CHOICES = [
        ('active', 'Active'),
        ('inactive', 'Inactive'),
    ]
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='active')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    # 运营监控字段 - 对应家庭空间页成员管理与健康档案
    member_count = models.IntegerField(default=1, help_text="家庭成员数量")
    active_member_count = models.IntegerField(default=1, help_text="活跃成员数量")
    last_activity_at = models.DateTimeField(null=True, blank=True, help_text="最后活跃时间")
    health_record_count = models.IntegerField(default=0, help_text="健康档案数量")

    def __str__(self):
        return str(self.name)


class FamilyMember(models.Model):
    ROLE_CHOICES = [
        ('admin', 'Admin'),
        ('member', 'Member'),
        ('viewer', 'Viewer'),
    ]
    
    family = models.ForeignKey(Family, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='member')
    relation = models.CharField(max_length=20)
    health_notes = models.TextField(blank=True)
    permissions = models.JSONField(blank=True, null=True)
    joined_at = models.DateTimeField(auto_now_add=True)
    
    # 运营监控字段 - 对应家庭空间页成员管理
    last_seen_at = models.DateTimeField(null=True, blank=True, help_text="最后在线时间")
    contribution_score = models.IntegerField(default=0, help_text="贡献分数")
    shared_record_count = models.IntegerField(default=0, help_text="共享记录数量")

    class Meta:
        unique_together = ('family', 'user')

    def __str__(self):
        return f"{self.user.username} - {self.family.name}"